package com.neuedu.config;


import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import jakarta.annotation.Resource;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
public class RedisConfig {
    @Resource
    RedisConnectionFactory connectionFactory;
    @Bean(name = "wyredis")
    RedisTemplate<String, Object> getRedisTemplate () {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new FastJsonRedisSerializer<Object>(Object.class));
        return redisTemplate;
    }
    @Bean
    CacheManager getCacheManager () {  // 缓存管理器 使多种语言都可以查看redis的缓存
        RedisCacheManager cacheManager = new RedisCacheManager(
                RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory),
                RedisCacheConfiguration.defaultCacheConfig()
                        .entryTtl(Duration.ofDays(120))  //配置缓存的默认过期时间为120天
                        .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new FastJsonRedisSerializer<Object>(Object.class)))
        );
        /**
         * 总结
         * 键：使用StringRedisSerializer，将键转换为字符串，再转换为字节流。
         * 值：使用FastJsonRedisSerializer，将值转换为JSON字符串，再转换为字节流。
         * 这样，在Redis中，键和值都是字符串，便于后续的调试和查看。
         */
        return cacheManager;
    }
}
